'use strict'

// <--    还原前    -->
function test(){
    if ('a' === 'b'){
        console.log('this is consenquent block')
    }else{
        console.log('this is alternate block')
    }
}

/**
 * <--    特点    -->
 * 1. 分支结构的条件判断为恒定值，直接决定该执行哪个语句块
 * 
 * <--    解决办法    -->
 * 1. 计算条件判断
 * 2. 进入相应语句块，将语句挨个插入到ifStmt之前
 * 3. 删除ifstmt
 * 
 * <--    冗余判断    -->
 * 分支结构的条件判断直接可求得值
 * 
 **/

// <--    还原后    -->
function test() {
    console.log('this is alternate block');
}
// <----------------->

const {parse} = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
const generator = require('@babel/generator').default;

let xcode = `function test(){
    if ('a' === 'b'){
        console.log('this is consenquent block')
    }else{
        console.log('this is alternate block')
    }
}`;

const visitor = {
    IfStatement:{
        enter: function(ifStmt){
            let {confident, value} = ifStmt.get('test').evaluate();
            if (confident){
                let blockStmt = value ? ifStmt.get('consequent.body') : ifStmt.get('alternate.body');
                for (let stmt of blockStmt){
                    ifStmt.insertBefore(stmt.node);
                }

                let program = ifStmt.parentPath;
                ifStmt.remove();
                program.scope.crawl();
            }
        },
    },
}

let ast = parse(xcode);
traverse(ast, visitor);
let {code} = generator(ast, {retainLines: false});

console.log(code);
